import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution872 {
    public void travel(TreeNode root,List<Integer> seq){
        boolean hasLeft=(root.left!=null);
        boolean hasRight=(root.right!=null);
        if(hasLeft) {travel(root.left,seq);}
        if(hasLeft==false&&hasRight==false) {seq.add(root.val);}
        if(hasRight) {travel(root.right,seq);}
    }


    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> seq_1=new ArrayList<>();
        List<Integer> seq_2=new ArrayList<>();
        travel(root1,seq_1);
        travel(root2,seq_2);
        return seq_1.equals(seq_2);
    }
}
